import datetime

from sqlalchemy import text
import json,os
import shutil
from win32com import client
from functools import partial
from flask import Blueprint, render_template, request,current_app,jsonify
from applications.extensions import db
import pythoncom
def reportprint(path,style='pdf',parms={}, fileds_items=[], subreport_parms={}, subreport_fileds_items=[]):
    # 初始化 COM 库
    pythoncom.CoInitialize()

    Report = client.Dispatch("gregn.GridppReport.6")  # 是com组件，engine

    if os.path.exists(path):
        Report.LoadFromFile(path)  # 加载打印模板
        Report.PrepareLoadData()  # 推模式，此语句要在前面定义好，表示不用数据库的数据
        # 创建打印数据

        if subreport_parms or subreport_fileds_items:
            SubReport = Report.ControlByName("SubReport1").AsSubReport.Report  # 子报表
            SubReport.PrepareLoadData()
            if subreport_parms:
                for k, v in parms.items():
                    if v == None:
                        v = ''
                    SubReport.ParameterByName(k).AsString = str(v)
            if subreport_fileds_items:
                for subreport_fileds_item in subreport_fileds_items:
                    SubReport.DetailGrid.Recordset.Append()  # 添加字段值的开始
                    for k, v in subreport_fileds_item.items():
                        if v == None:
                            v = ''
                        SubReport.FieldByName(k).AsString = str(v)  # 对字段赋值
                    SubReport.DetailGrid.Recordset.Post()  # 添加字段值的结束
        if parms or fileds_items:
            if parms:
                for k, v in parms.items():
                    if v == None:
                        v = ''
                    Report.ParameterByName(k).AsString = str(v)
            if fileds_items:
                for fileds_item in fileds_items:
                    Report.DetailGrid.Recordset.Append()  # 添加字段值的开始
                    for k, v in fileds_item.items():
                        if v == None:
                            v = ''
                        Report.FieldByName(k).AsString = str(v)  # 对字段赋值
                    Report.DetailGrid.Recordset.Post()  # 添加字段值的结束

        if style=='pdf':
            Path = os.path.dirname(os.path.abspath("__file__"))

            temp_file= "报表"+datetime.datetime.now().strftime('%Y%m%d%H%M%S')+'.pdf'
            temp_path=os.path.join(Path,'static','temp',temp_file)
            print(temp_path)
            try:
                ExportOption = Report.PrepareExport(5)  # 设置导出参数
                ExportOption.AbortOpenFile = False  # 指定报表在导出为文档之后是否用关联程序打开该导出文档。True为不指定

                ExportOption.FileName =temp_path

                ExportOption.AsE2PDFOption.FontEmbedding=True #关联字体

                ExportOption.AbortShowOptionDlg=True

                bool=Report.Export(False)  # 设置导出文件打开
                print(bool)
                Report.UnprepareExport()  # 释放资源
                if bool :
                    return '/h5/static/temp/'+temp_file
                else:
                    return ''
                # Report.ExportDirect(5,r'E:\pear-admin-flask\temp\1.pdf',True,False) #另一种方法，报错，没有关联字体
            except Exception as e:
                print(e)
                return ''

def reportPrintToPdf():
    '''
    res = {
        'msg': msg,
        'code': 0,
        'pdfurl': data,

    }
    '''
    res={'msg': '',
        'code': 0,
        'pdfurl': ''}
    # 获取请求参数
    reportstyleinfo = json.loads(request.args.get('reportstyleinfo', '{}'))
    fileds_items = json.loads(request.args.get('fileds_items', '[]'))
    print(reportstyleinfo,fileds_items)
    realPath = ''
    if reportstyleinfo:
        realPath = './' + reportstyleinfo.get('href', '').replace('/_uploads/reports/', 'static/upload/report/')
        realPath = os.path.abspath(realPath)
        if os.path.isfile(realPath):
            pdfurl=reportprint(path=realPath)
            if pdfurl:
                res['pdfurl'] = pdfurl
            else:
                res['code'] = 400
                res['msg'] = '生成pdf文件失败'

        else:
            res['code'] = 400
            res['msg'] = '未找到相应报表路径'
    else:
        res['code'] =400
        res['msg'] = '未找到相应报表路径'




    print(realPath)




    return jsonify(res)






